from sanic import response
from sanic import Blueprint
import hashlib
from config import WECHAT_APPID, WECHAT_SECRET, WECHAT_TOKEN, MSG_TEMPLATE_ID
from wechat import receive, reply, utility
import ujson as json

wechat = Blueprint('wechat_blueprint')
client = utility.WechatClient(WECHAT_APPID, WECHAT_SECRET, WECHAT_TOKEN)

def wechat_check_msg_valid(data):
    signature = data['signature']
    timestamp = data['timestamp']
    nonce = data['nonce']
    echostr = data['echostr']
    token = WECHAT_TOKEN

    args = [token, timestamp, nonce]
    args.sort()
    s = "".join(args)
    hashcode = hashlib.sha1(bytes(s, 'utf8')).hexdigest()
    return hashcode == signature


@wechat.get('/interface')
async def wechat_validate(request):
    data = request.raw_args
    echostr = data['echostr']
    valid = wechat_check_msg_valid(data)
    if valid:
        return response.text(echostr)
    else:
        return response.text("Hello world")

@wechat.get('/token')
async def wechat_token(request):
    token = await client.get_token()
    return response.text(token)

@wechat.post('/interface')
async def wechat_msg(request):
    rec_msg = receive.parse_xml(request.body)
    if isinstance(rec_msg, receive.TextMsg):
        content = "Location event"
        reply_msg = reply.TextMsg(rec_msg, content)
        return response.text(reply_msg.send())
    elif isinstance(rec_msg, receive.LocationEvent):
        content = "Location event"
        reply_msg = reply.TextMsg(rec_msg, content)
        return response.text(reply_msg.send())
    elif isinstance(rec_msg, receive.MenuEvent):
        content = "Key pressed, key value is: {}".format(rec_msg.EventKey)
        reply_msg = reply.TextMsg(rec_msg, content)
        return response.text(reply_msg.send())
